package cn.jji8.QSGUI.Gui;

import cn.jji8.QSGUI.Gui.Goods.Goods;
import cn.jji8.QSGUI.quick.logger.Language;
import cn.jji8.QSGUI.quick.logger.Logger;
import cn.jji8.QSGUI.quick.tool.Number;
import org.bukkit.entity.HumanEntity;
import org.bukkit.entity.Player;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.inventory.Inventory;
import org.maxgamer.quickshop.shop.Shop;

import java.util.HashMap;
import java.util.Map;

public class Gui {
    //static
    static Map<Shop,Gui> GuiMap = new HashMap<>();
    /**
     * 获取一个gui
     * */
    static Gui getGui(Shop shop){
        Gui returnGui = GuiMap.get(shop);
        if(returnGui==null){
            GuiMap.put(shop,returnGui = new Gui(shop));
        }
        return returnGui;
    }
    public static void reload(){
        GuiMap = new HashMap<>();
    }

    //no static
    Shop shop;
    Map<Integer, Goods> goodsMap = new HashMap<>();
    Gui(Shop shop){
        this.shop = shop;
        if(shop.isBuying()){
            GuiConfigLoad.loadBuyConfig(this);
        }else {
            GuiConfigLoad.loadSellConfig(this);
        }
    }
    /**
     * 向gui中添加一个goods
     * */
    public void addGoods(int x,int y,Goods goods){
        int p = (y-1)*9+x;
        goodsMap.put(p,goods);
    }
    /**
     * 当玩家点击gui时会被调用
     * */
    public void click(InventoryClickEvent a){
        Logger.putdebug(a.getWhoClicked().getName()+"玩家点击了gui");
        a.setCancelled(true);
        Goods goods = goodsMap.get(a.getRawSlot()+1);
        if(goods!=null){
            Logger.putdebug(a.getWhoClicked().getName()+"玩家点击了gui中的"+a.getRawSlot()+1+"物品");
            HumanEntity player = a.getWhoClicked();
            goods.click(a);
        }
    }
    /**
     * 给玩家打开当前商店页面
     * */
    public void open(Player player) {
        Inventory inventory;
        Map<String,Object> map = new HashMap<>();
        map.put("%单价%", Number.XianShiZiFu(shop.getPrice()));
        if(shop.isBuying()){
            inventory = org.bukkit.Bukkit.createInventory(null,27, Language.get("箱子标题收购商店","§d§l收购商店 §g收购物品价格:%单价%元/个",map));
        }else {
            inventory = org.bukkit.Bukkit.createInventory(null,27, Language.get("箱子标题出售商店","§d§l出售商店 §g出售物品价格:%单价%元/个",map));
        }
        for(int i=0;i<27;i++){
            Goods goods = goodsMap.get(i+1);
            if(goods!=null){
                inventory.setItem(i,goods.getItemStack(player));
            }
        }
        player.openInventory(inventory);
    }
}
